<template>
  <button class="back-to-top" v-show="visible" @click="scrollToTop" aria-label="回到顶部">
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M12 19V5M5 12L12 5L19 12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
    </svg>
  </button>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'

const visible = ref(false)
let scrollTimer: number | null = null

const handleScroll = () => {
  // 清除之前的定时器
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }
  
  // 设置新的定时器，优化滚动性能
  scrollTimer = window.setTimeout(() => {
    visible.value = window.scrollY > 300
  }, 100)
}

const scrollToTop = () => {
  // 使用缓动函数实现平滑滚动效果
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const duration = 600 // 动画持续时间
  const startTime = performance.now()

  const animateScroll = (currentTime: number) => {
    const elapsed = currentTime - startTime
    const progress = Math.min(elapsed / duration, 1)
    
    // 使用缓动函数: easeOutQuad (先快后慢)
    const easeOutQuad = (t: number) => t * (2 - t)
    const easedProgress = easeOutQuad(progress)
    
    const scrollTo = scrollTop * (1 - easedProgress)
    
    window.scrollTo(0, scrollTo)
    
    if (progress < 1) {
      requestAnimationFrame(animateScroll)
    }
  }
  
  requestAnimationFrame(animateScroll)
}

onMounted(() => {
  window.addEventListener('scroll', handleScroll)
  // 初始化时检查一次滚动位置
  handleScroll()
  
  // 确保visible在页面滚动足够时初始化为true
  if (window.scrollY > 300) {
    visible.value = true
  }
})

onBeforeUnmount(() => {
  window.removeEventListener('scroll', handleScroll)
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }
})
</script>

<style scoped>
.back-to-top {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(100, 108, 255, 0.8);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: white;
  border: none;
  padding: 0;
  margin: 0;
}

.back-to-top:hover {
  background: rgba(100, 108, 255, 0.9);
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.back-to-top svg {
  transition: transform 0.3s ease;
  width: 20px;
  height: 20px;
}

.back-to-top:hover svg {
  transform: translateY(-2px);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .back-to-top {
    width: 36px;
    height: 36px;
    bottom: 15px;
    right: 15px;
  }
  
  .back-to-top svg {
    width: 18px;
    height: 18px;
  }
}

@media (max-width: 480px) {
  .back-to-top {
    width: 32px;
    height: 32px;
    bottom: 10px;
    right: 10px;
  }
  
  .back-to-top svg {
    width: 16px;
    height: 16px;
  }
}
</style>